package org.fall.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.fall.system.constant.BackstageConstant;
import org.fall.system.dao.AdminUserMapper;
import org.fall.system.model.ResultEntity;
import org.fall.system.model.dto.AdminUserDTO;
import org.fall.system.model.po.AdminUserPO;
import org.fall.system.service.BackstageIndexService;
import org.fall.system.utils.AdminCommonTool;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author zjh
 * @since 2021/3/19 16:13
 */
@Service
public class BackstageIndexServiceImpl implements BackstageIndexService {

    @Resource
    private AdminUserMapper adminUserMapper;


    @Override
    public ResultEntity login(AdminUserDTO dto, HttpSession session) {
        QueryWrapper<AdminUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(BackstageConstant.USERNAME, dto.getUsername());
        queryWrapper.eq(BackstageConstant.PASSWORD, dto.getPassword());
        List<AdminUserPO> list = adminUserMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            return ResultEntity.failed(BackstageConstant.LOGIN_FAILED);
        }
        AdminUserPO adminUser = list.get(0);
        if (adminUser.getStatus() == 0) {
            return ResultEntity.failed(BackstageConstant.USER_UNAVAILABLE);
        }
        session.setAttribute("loginUser", adminUser.getName());
        session.setAttribute("userLevel", adminUser.getLevel());
        return ResultEntity.successWithData(adminUser.getName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultEntity register(AdminUserDTO dto) {
        QueryWrapper<AdminUserPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(BackstageConstant.USERNAME, dto.getUsername());
        Integer count = adminUserMapper.selectCount(queryWrapper);
        if (count >= 1) {
            return ResultEntity.failed(BackstageConstant.USERNAME_EXIST);
        }
        // 注册操作
        AdminUserPO po = new AdminUserPO();
        BeanUtils.copyProperties(dto, po);
        Integer level = dto.getLevel();
        // 角色与等级操作
        po.setRole(AdminCommonTool.getRoleByLevel(level));
        // 执行新增操作
        int res = adminUserMapper.insert(po);
        if (res == 1) {
            return ResultEntity.successWithoutData();
        }
        return ResultEntity.failed(BackstageConstant.REGISTER_FAILED);
    }
}
